package com.tsmti.webservice.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.i18n.LocaleContextHolder;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Date Utility Class used to convert Strings to Dates and Timestamps
 *
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 *         Modified by <a href="mailto:dan@getrolling.com">Dan Kibler </a>
 *         to correct time pattern. Minutes should be mm not MM (MM is month).
 */
public final class DateUtil {
    private static Log log = LogFactory.getLog(DateUtil.class);
    private static final String TIME_PATTERN = "HH:mm";
    private static SimpleDateFormat SHORT_FORMAT = new SimpleDateFormat(
            "yyyy-MM-dd");
    private static SimpleDateFormat LONG_FORMAT = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");
    private static SimpleDateFormat LONG_LONG_FORMAT = new SimpleDateFormat(
            "yyyy-MM-dd'T'HH:mm:ss.SSS");
    /**
     * Checkstyle rule: utility classes should not have public constructor
     */
    private DateUtil() {
    }

    /**
     * Return default datePattern (MM/dd/yyyy)
     *
     * @return a string representing the date pattern on the UI
     */
    public static String getDatePattern() {
        Locale locale = LocaleContextHolder.getLocale();
        String defaultDatePattern;
        try {
            defaultDatePattern = ResourceBundle.getBundle("ApplicationResources", locale)
                    .getString("date.format");
        } catch (MissingResourceException mse) {
            defaultDatePattern = "MM/dd/yyyy";
        }

        return defaultDatePattern;
    }
    public static String getShortCurrentDate() {
        return new String(SHORT_FORMAT.format(new Date()));
    }
    public static String getLongCurrentDate() {
        return new String(LONG_FORMAT.format(new Date()));
    }
    public static String getLongLongCurrentTime() {
        return new String(LONG_LONG_FORMAT.format(new Date()));
    }
    public static String getLongDate(Date date) {
        return new String(LONG_FORMAT.format(date));
    }
    public static Date parseLongDate(String timeText) {
        try {
            if (timeText != null){
                return LONG_FORMAT.parse(timeText);
            }
        } catch (ParseException parseexception) {
            return null;
        }
        return null;
    }

    public static String getDateTimePattern() {
        return DateUtil.getDatePattern() + " HH:mm:ss.S";
    }

    /**
     * This method attempts to convert an Oracle-formatted date
     * in the form dd-MMM-yyyy to mm/dd/yyyy.
     *
     * @param aDate date from database as a string
     * @return formatted string for the ui
     */
    public static String getDate(Date aDate) {
        SimpleDateFormat df;
        String returnValue = "";

        if (aDate != null) {
            df = new SimpleDateFormat(getDatePattern());
            returnValue = df.format(aDate);
        }

        return (returnValue);
    }

    /**
     * This method generates a string representation of a date/time
     * in the format you specify on input
     *
     * @param aMask the date pattern the string is in
     * @param strDate a string representation of a date
     * @return a converted Date object
     * @throws ParseException when String doesn't match the expected format
     * @see SimpleDateFormat
     */
    public static Date convertStringToDate(String aMask, String strDate)
            throws ParseException {
        SimpleDateFormat df;
        Date date;
        df = new SimpleDateFormat(aMask);

        if (log.isDebugEnabled()) {
            log.debug("converting '" + strDate + "' to date with mask '" + aMask + "'");
        }

        try {
            date = df.parse(strDate);
        } catch (ParseException pe) {
            throw new ParseException(pe.getMessage(), pe.getErrorOffset());
        }

        return (date);
    }

    /**
     * This method returns the current date time in the format:
     * MM/dd/yyyy HH:MM a
     *
     * @param theTime the current time
     * @return the current date/time
     */
    public static String getTimeNow(Date theTime) {
        return getDateTime(TIME_PATTERN, theTime);
    }

    /**
     * This method returns the current date in the format: MM/dd/yyyy
     *
     * @return the current date
     * @throws ParseException when String doesn't match the expected format
     */
    public static Calendar getToday() throws ParseException {
        Date today = new Date();
        SimpleDateFormat df = new SimpleDateFormat(getDatePattern());

        // This seems like quite a hack (date -> string -> date),
        // but it works ;-)
        String todayAsString = df.format(today);
        Calendar cal = new GregorianCalendar();
        cal.setTime(convertStringToDate(todayAsString));

        return cal;
    }

    /**
     * This method generates a string representation of a date's date/time
     * in the format you specify on input
     *
     * @param aMask the date pattern the string is in
     * @param aDate a date object
     * @return a formatted string representation of the date
     * @see SimpleDateFormat
     */
    public static String getDateTime(String aMask, Date aDate) {
        SimpleDateFormat df = null;
        String returnValue = "";

        if (aDate == null) {
            log.warn("aDate is null!");
        } else {
            df = new SimpleDateFormat(aMask);
            returnValue = df.format(aDate);
        }

        return (returnValue);
    }

    /**
     * This method generates a string representation of a date based
     * on the System Property 'dateFormat'
     * in the format you specify on input
     *
     * @param aDate A date to convert
     * @return a string representation of the date
     */
    public static String convertDateToString(Date aDate) {
        return getDateTime(getDatePattern(), aDate);
    }

    /**
     * This method converts a String to a date using the datePattern
     *
     * @param strDate the date to convert (in format MM/dd/yyyy)
     * @return a date object
     * @throws ParseException when String doesn't match the expected format
     */
    public static Date convertStringToDate(final String strDate) throws ParseException {
        return convertStringToDate(getDatePattern(), strDate);
    }

    /**
     * @return 返回当前时间字符，格式为 yyyy'-'MM'-'dd
     *
     * 返回当前时间字符，默认格式为yyyy'-'MM'-'dd
     *
     * 如 2004-09-07
     */
    public static String getCurrentDateString() {
        String timestrformart = "yyyy'-'MM'-'dd" ;
        SimpleDateFormat sdf = new SimpleDateFormat(timestrformart) ;
        Calendar calendar = Calendar.getInstance() ;

        return sdf.format(calendar.getTime()) ;
    }
    /**
     * 两个时间相差距离多少天多少小时多少分多少秒
     * @param date1 时间参数 1 格式：1990-01-01 12:00:00
     * @param date2 时间参数 2 格式：2009-01-01 12:00:00
     * @return String 返回值为：xx天xx小时xx分xx秒
     */
    public static String getDistanceTime(Date date1, Date date2) {
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        try {
            long time1 = date1.getTime();
            long time2 = date2.getTime();
            long diff ;
            if(time1<time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            day = diff / (24 * 60 * 60 * 1000);
            hour = (diff / (60 * 60 * 1000));
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            sec = (diff/1000-day*24*60*60-hour*60*60-min*60);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return hour + "小时" + min + "分";
    }

    public static String parseShortDate(Date date) {
        return new String(SHORT_FORMAT.format(date));
    }


    /**
     * 获取当前时间 Date 类型，为空则默认类型为yyyy-MM-dd HH:mm:ss 格式的数据  ymc_u
     * @return NowDateTime
     */
    public static Date getCurrentDateTime(String format){
        if(null == format || "".equals(format) ){
            format = "yyyy-MM-dd HH:mm:ss";
        }
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat(format);
        // new Date()为获取当前系统时间
        String sendTime=df.format(new Date());
        Date date =null;
        try {
             date=df.parse(sendTime) ;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 取当前时间 返回String
     * @param format
     * @return
     */
    public static String getCurrentStringTime(String format){
        if(null == format || "".equals(format) ){
            format = "yyyy-MM-dd HH:mm:ss";
        }
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat(format);
        // new Date()为获取当前系统时间
        String sendTime=df.format(new Date());
        return sendTime;
    }

}
